#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define x first 
#define y second
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int h[N], ne[N], w[N], e[N], index;
int dis[N];
bool st[N];
int n, m;

void add(int a, int b, int u)
{
	e[index] = b;
	ne[index] = h[a];
	w[index] = u;
	h[a] = index++;
}
int dijkstra()
{
	memset(dis, 0x3f, sizeof(dis));
	dis[1] = 0;
	priority_queue<PII,vector<PII>,greater<PII> >heap;
	heap.push({ 1,0 });
	while (!heap.empty()) {
		PII t = heap.top();
		heap.pop();
		int ver = t.x;
		int distance = t.y;
		if (st[ver])  continue;
		st[ver] = 1;
		for (int i = h[ver]; i != -1; i = ne[i]) {
			int j = e[i]; 
			if (!st[j] && dis[j] > distance + w[i]) {
				dis[j] = distance + w[i];
				heap.push({ dis[j],j });
			}
		}
		
	}
	if (dis[n] == 0x3f3f3f3f)return -1;
	return dis[n];
}
int main()
{
	cin >> n >> m;
	memset(h, -1 , sizeof(h));
	while (m--) {
		int a, b, u;
		cin >> a >> b >> u;
		add(a, b, u);
	}
	int ret = dijkstra();
	cout << ret << endl;
	return 0;
}